<template>
  <div :style="divimg">
    <div style="padding-top: 10%;width: 100%;height: 100%;">

      <div style="margin-left: 35%">
        <el-tabs v-model="activeName" style="width: 45%">
          <el-tab-pane label="账户登录" name="first">
            <el-form ref="form" :model="form" label-width="80px" style="width: 100%">
              <el-form-item label="用户名">
                <el-input placeholder="请输入登录名" v-model="form.userName"></el-input>
              </el-form-item>
              <el-form-item label="密码">
                <el-input placeholder="请输入密码" v-model="form.password" show-password></el-input>
              </el-form-item>
              <el-form-item>
                <el-checkbox v-model="checked" style="color:black">一周内自动登录</el-checkbox>
                <el-button type="primary" @click="onSubmit" style="width: 100%">登录</el-button>


              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="短信登录/邮箱登录" name="second">

            <el-form ref="form" :model="form" label-width="80px" style="width: 100%">
              <el-form-item label="手机/邮箱">
                <el-input placeholder="请输入手机号/邮箱" v-model="form.userName"></el-input>
              </el-form-item>
              <el-form-item label="验证码">
                <el-input placeholder="请输入内容" v-model="form.password">
                  <el-button slot="append" @click="getMessageCode">点击获取验证码</el-button>
                </el-input>
              </el-form-item>
              <!--一周内免登录-->

              <el-form-item>

                <el-button type="primary" @click="onSubmitMessage" style="width: 100%">登录</el-button>

              </el-form-item>
            </el-form>

          </el-tab-pane>
        </el-tabs>


        <el-breadcrumb separator="|" style="margin-left:20%;margin-top: 50px">
          <el-breadcrumb-item>
            <el-link @click="toRegister">立即注册</el-link>
          </el-breadcrumb-item>
          <el-breadcrumb-item>
            <el-link @click="forgetPassword">忘记密码</el-link>
          </el-breadcrumb-item>
        </el-breadcrumb>

      </div>

      <!--    <img src="http://148.70.46.222:9000/test/013.png"/>-->

    </div>
  </div>
</template>

<script>
    import CryptoJS from "crypto-js";
  export default {
    name: "login",
    data() {
      return {
        divimg: { //背景图片的使用
          backgroundImage: "url(" + require('../../assets/4.jpg') + ")",
          backgroundRepeat: "no-repeat",
          height: "100%",
          width: "100%",
          overflow: "hidden",
          backgroundSize: "cover"
        },
        activeName: 'first',
        form: {
          userName: '',
          password: '',
          tel: "",
          code: ""
        },
          checked:false
      }
    },
      created(){
          this.getCookie();
      },
    methods: {
      onSubmit() {
          //保存的账号
          var name=this.form.userName;
          //保存的密码
          var pass=this.form.password;
          //判断复选框是否被勾选 勾选则调用配置cookie方法
          if(this.checked==true){
              //传入账号名，密码，和保存天数3个参数
              this.setCookie(name,pass,7);
              this.setCookie(name,pass,7);
          }


        this.$axios.post(this.$gloableData.serverPath + "auth/forLogin", this.$data.form).then((response) => {

          if (response.data.code == 1006) {
            //存储Token到本地
            window.localStorage.removeItem("token")
            window.localStorage.setItem("token", response.headers["token"])
              window.localStorage.setItem("userInfo",  response.data.userInfo)
            let name = response.data.userInfo;
            console.log(name);
            //跳转到home界面
            this.$router.push({
              name: "home",
              params: {
                name: name
              }
            });
            //存储用户信息，这是一个用户的登录名
            let loginName = "" + response.data.userInfo;
           // this.$store.state.userId = uuid;

          } else {
            this.$message.error('登录失败，用户名或密码错误！');
          }
        })
        //     .catch((error => {
        //   this.$message.error(JSON.stringify(error.data));
        // }))
        ;
      },
        setCookie(portId, psw, exdays) {
            // Encrypt，加密账号密码
            var cipherPortId = CryptoJS.AES.encrypt(
                portId+'',
                "secretkey123"
            ).toString();
            var cipherPsw = CryptoJS.AES.encrypt(psw+'', "secretkey123").toString();
            alert(cipherPortId+'/'+cipherPsw)
            console.log(cipherPortId+'/'+cipherPsw)//打印一下看看有没有加密成功

            var exdate = new Date(); //获取时间
            exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays); //保存的天数
            //字符串拼接cookie，为什么这里用了==，因为加密后的字符串也有个=号，影响下面getcookie的字符串切割，你也可以使用更炫酷的符号。
            window.document.cookie =
                "userName" +
                "==" +
                cipherPortId +
                ";path=/;expires=" +
                exdate.toGMTString();
            window.document.cookie =
                "password" +
                "==" +
                cipherPsw +
                ";path=/;expires=" +
                exdate.toGMTString();
        },
        //读取cookie
        getCookie: function() {
            if (document.cookie.length > 0) {
                var arr = document.cookie.split("; "); //这里显示的格式请根据自己的代码更改

                for (var i = 0; i < arr.length; i++) {
                    var arr2 = arr[i].split("=="); //根据==切割
                    //判断查找相对应的值
                    if (arr2[0] == "userName") {
                        // Decrypt，将解密后的内容赋值给账号
                        var bytes = CryptoJS.AES.decrypt(arr2[1], "secretkey123");
                        this.form.userName = bytes.toString(CryptoJS.enc.Utf8);
                        alert(this.form.userName)
                    } else if (arr2[0] == "password") {
                        // Decrypt，将解密后的内容赋值给密码
                        var bytes = CryptoJS.AES.decrypt(arr2[1], "secretkey123");
                        this.form.password= bytes.toString(CryptoJS.enc.Utf8);
                        alert(this.form.password)
                    }
                }
                this.onSubmit();
            }
        },

      onSubmitMessage() {
        this.$axios.post(this.$gloableData.serverPath + "auth/forLogin", this.$data.form).then((response) => {

          if (response.data.code == 1006) {
            //存储Token到本地
            window.localStorage.removeItem("token")
            window.localStorage.setItem("token", response.headers["token"])
            window.localStorage.setItem("loginName",this.form.userName)
              window.localStorage.setItem("userInfo",  response.data.userInfo)

            let name = response.data.userInfo;
            console.log(name);
            //跳转到home界面
            this.$router.push({
              name: "home",
              params: {
                name: name
              }
            });
            //存储用户信息，这是一个用户的登录名
            let loginName = "" + response.data.userInfo;
            window.localStorage.setItem("userInfo", userName)
          } else {
            this.$message.error('登录失败，手机号或验证码错误！');
          }
        }).catch((error => {
          this.$message.error(JSON.stringify(error.data));
        }));
      },
      getMessageCode() {
        this.$axios.get(this.$gloableData.serverPath + "auth/smsyzm", {
          params: {
            phone: this.form.userName
          }
        }).then((response) => {
          if (response.data) {
            this.$message({
              message: '获取验证码成功',
              type: 'success'
            });
          } else {
            this.$message('获取失败/格式不正确');
          }
        })
      },
      toRegister() {
        this.$router.push("/register")
      },
      forgetPassword() {
        this.$router.push("/forgetPass")
      }
    }
  }
</script>
<style scoped>

</style>
